# -*- coding:utf8 -*-

from Crypto.Hash import keccak

from web3 import Web3
from eth_account import Account

import click
import os
import base64

@click.group()
def cli():
    pass

@cli.command()
@click.option('--priv', default = None, help="input ur priv key with hex")
def gen_acc(priv):
    if priv == None:
        account = Account.create()
    else:
        account = Account.privateKeyToAccount(priv)
    print("priv: {priv_key} \npub: {pub_key} \naddr: {addr}".format(priv_key=account.privateKey.hex(),
    pub_key=int(account._key_obj.public_key.to_hex(),16),
    addr=account.address))

@cli.command()
@click.option('--priv', help="input ur priv key with hex")
@click.option('--raw_tx',help="raw tx get by weid-rest-service")
def gen_sig(priv, raw_tx):
    account = Account.privateKeyToAccount(priv)
    raw_tx_bytes = base64.b64decode(raw_tx)

    msg = keccak.new(digest_bits=256)
    msg.update(raw_tx_bytes)

    sig = account.signHash(msg.digest())
    if (len(hex(sig.r)[2:]) % 2) == 0:
        hexed_r = hex(sig.r)[2:]
    else:
        hexed_r = "0" + hex(sig.r)[2:]
    if (len(hex(sig.s)[2:]) % 2) == 0:
        hexed_s = hex(sig.s)[2:]
    else:
        hexed_s = "0" + hex(sig.s)[2:]
    b_sig = bytes(bytearray.fromhex(hex(sig.v)[2:] + hexed_r + hexed_s))
    b_64_sig = base64.b64encode(b_sig).decode()
    print("sig: {sig}".format(sig=b_64_sig))

if __name__ == '__main__':
    cli()